<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 
 *
 */
class Dzdgs extends Backend
{
    /**
     * Dzdgs模型对象
     * @var \app\admin\model\Dzdgs
     */
    protected $model = null;
    
    protected $quickSearchField = ['ID'];

    protected $defaultSortField = 'ID,desc';

    protected $preExcludeFields = [''];
    protected $noNeedLogin      = ['*'];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\Dzdgs;
    }
    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $wheres='';
        foreach ($where as $k=>$item) {
            $wheres[]=['x_potsq.'.substr( $item[0],strripos( $item[0],".")+1),$item[1],$item[2]];

        }
        $res = $this->model
            ->field('dzdgs.*,DEPARTMENT.DEPTNAME')
            ->join('DEPARTMENT',"dzdgs.OPDEPT=DEPARTMENT.DEPTID")
            ->alias($alias)
            ->where($wheres)
            ->paginate($limit);
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $add=[];
            $adminInfo          = $this->auth->getInfo();
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                foreach ($data['DZDGSDETAIL'] as $k=>$v) {

                        $add[]=[
                            'GSID'=>$this->model->ID,
                            'TABLENAME'=>$v['TABLENAME'],
                            'COLNAME'=>$v['COLNAME'],
                            'COLLABEL'=>$v['COLLABEL'],
                            'SORTNO'=>$k,
                            'OP'=>$adminInfo['nickname'],
                            'OPTIME'=>date('Y-m-d H:i:s',time()),
                        ];

                }
                Db::table('DZDGSDETAIL')->insertAll($add);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            $adminInfo          = $this->auth->getInfo();
            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                $add=[];
                foreach ($data['DZDGSDETAIL'] as $k=>$v) {

                        $add[]=[
                            'GSID'=>$id,
                            'TABLENAME'=>$v['TABLENAME'],
                            'COLNAME'=>$v['COLNAME'],
                            'COLLABEL'=>$v['COLLABEL'],
                            'SORTNO'=>$k,
                            'OP'=>$adminInfo['nickname'],
                            'OPTIME'=>date('Y-m-d H:i:s',time()),
                        ];

                }
                Db::table('DZDGSDETAIL')->where('GSID',$id)->delete();
                Db::table('DZDGSDETAIL')->insertAll($add);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        $GSDETAIL=Db::table('DZDGSDETAIL')->where('GSID',$id)->order('SORTNO','asc')->select()->toArray();
        $column=Db::table('dzdcolumn')->where("COLNAME!=   all (select COLNAME from DZDGSDETAIL where GSID=$id )")->order('SORTNO','asc')->select()->toArray();
        $row['all']=array_merge($GSDETAIL,$column);
        $this->success('', [
            'row' => $row
        ]);
    }
    public function dzdcolumn($where=''){
        $data=Db::table('dzdcolumn')->where($where)->order('SORTNO','desc')->select();
        $this->success('',$data);
    }
}